import { Middleware, IMiddleware, Inject } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';
import { NextFunction, Context } from '@midwayjs/koa';
// import privacy from '../privacy';

@Middleware()
export class UserMiddleware implements IMiddleware<Context, NextFunction> {
    @Inject()
    jwtService: JwtService;


    resolve() {
        //       上下文   ctx: Context 等价我们 express  req  req.body req.header  
        //   next()
        return async (ctx: Context, next: NextFunction) => {

            //  中间 对方的token  就可以了
            //  想要获取token
            console.log(ctx.request.header.authorization);

            if (ctx.request.header.token || ctx.request.header.authorization) {
                console.log("token", ctx.request.header.token);
                let token = ctx.request.header.token || ctx.request.header.authorization.split(" ")[1]

                //  得到token 以后 将  用户信息放到上下文去 供下一个函数 使用
                try {
                    this.jwtService.verifySync(token + "", { complete: true })
                } catch {
                    return { code: 40002, message: "权限过期" }
                }
                await next()
            } else {
                return { code: 40001, message: "权限校验失败" }
            }
        };
    }



}